namespace Isolation.TeamFoundationServer
{
	#region #using Directives

	using System;
	using System.Collections.Generic;

	using Microsoft.TeamFoundation.WorkItemTracking.Client;

	#endregion

	public class TfsQuery : ITfsQuery
	{
		private readonly Query query;

		public TfsQuery(ITfsWorkItemStore workItemStore, string wiql)
		{
			this.query = new Query(((TfsWorkItemStore) workItemStore).TfsStore, wiql);
		}

		#region Implementation of ITfsQuery

		public ICancelableAsyncResult BeginQuery(AsyncCallback callback)
		{
			return new CancelableAsyncResult(this.query.BeginQuery(callback));
		}

		public ICollection<IWorkItem> EndQuery(ICancelableAsyncResult car)
		{
			try
			{
				var workItemCollection = this.query.EndQuery(((CancelableAsyncResult) car).TfsObject);
				var workItemList = new List<IWorkItem>(workItemCollection.Count);

				foreach (Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem workItem in workItemCollection)
				{
					workItemList.Add(new WorkItem(workItem));
				}

				return workItemList;
			}
			catch (ConnectionException ce)
			{
				throw new TfsConnectionException(ce);
			}
		}

		#endregion
	}
}